<?php

class Middleman_Plugin_Acl extends Zend_Controller_Plugin_Abstract {

    private $_acl = null;
    private $_auth = null;

    public function __construct(Zend_Acl $acl=null, Zend_Auth $auth) {
        $this->_acl = $acl;
        $this->_auth = $auth;
    }
    public function getRole(){
        //current user id 
        $id = $this->_auth->getIdentity()->id;
        $model = new Application_Model_DbTable_User();
        $user = $model->find($id)->current();
        $role = $user->findManyToManyRowset('Application_Model_DbTable_Role', 'Application_Model_DbTable_RoleUser')->toArray();
        return (is_array($role)?$role[0]['name']:"guest");
        
    }
    public function preDispatch(Zend_Controller_Request_Abstract $request) {
        //As in the earlier example, authed users will have the role user
        
        //For this example, we will use the controller as the resource:
        $resource = $request->getControllerName();
        $privilege = $request->getActionName();
        if(!$this->_auth->hasIdentity()){
            $request
                    ->setControllerName('user')
                    ->setActionName('login');
        }
        
        else if (!$this->_acl->isAllowed($this->getRole(), $resource, $privilege)) {
            //If the user has no access we send him elsewhere by changing the request
            $request
                    ->setControllerName('error')
                    ->setActionName('noaccess');
        }
    }

}